package tool.soft

import java.io.File
import command.CommandExec
import dao._
import models.Tables
import org.joda.time.DateTime
import play.api.mvc.{AnyContent, Request}
import play.twirl.api.Html
import shared.Pojo._
import tool.Pojo._
import tool._
import tool.plot._
import tool.soft.AllSoft.SoftBT

import scala.collection.immutable.SeqMap
import implicits.Implicits._
import models.Tables._
import play.api.data.FormBinding
import play.api.i18n.Messages
import upickle.default._
import utils.Utils

/** Created by yz on 15/9/2020
  */
object DiffAnaMulSoft extends DiffAnaMulSoftT with SoftBT {

  override def getResultFileName: String = {
    "Diff_Metabolite.csv"
  }

  override def getFileInfos(workspaceDir: File, index: Int)(implicit
      matrixFileDataDao: MatrixFileDataDao,
      messages: Messages
  ): List[FileInfoData] = {
    List(
      FileInfoData("AllMet_Test.csv", messages("allMetTest")),
      FileInfoData("Diff_Met_Test.csv", messages("diffMetTest")),
      FileInfoData("AllMet_Z_Score.csv", messages("allMetZScore")),
      FileInfoData("Z_Score_Plot.pdf", messages("zScorePlot")),
      FileInfoData("Diff_Metabolite.csv", messages("diffMetabolite"))
    )
  }

  override def produceConfigFile(workspaceDir: File, index: Int)(implicit
      request: Request[AnyContent],
      formBinding: FormBinding
  ) = {
    plot.ZScore.initConfigFile(workspaceDir, idStr = "")
    Utils.t2ConfigFile(data, Tool.getCalculateConfigJsonFile(workspaceDir))
  }

  def getArg(implicit request: Request[AnyContent], messages: Messages, formBinding: FormBinding): ujson.Value = {
    val methodStr = Tool.getMulMethod(data.method)
    val fdrMap = if (data.useFdr) {
      SeqMap(messages("fDRCutoff") -> data.fdr)
    } else {
      SeqMap[String, String]()
    }
    val argMap = SeqMap(messages("analysisMethod") -> methodStr, messages("pValueCutoff") -> data.pValue) ++ fdrMap
    writeJs(argMap)
  }

  override def getResultHtml(missionId: Int)(implicit request: Request[AnyContent], messages: Messages): Html = {
    views.html.user.mission.diffAnaMulResult(missionId)
  }

  override def getCommandData(workspaceDir: File, resultDir: File, index: Int): List[CommandData] = {
    val groupFile = new File(workspaceDir, "group.txt")
    val solutionFile = new File(Tool.dataDir, "color_solution/color_solution_1.txt")
    val command =
      s"""
         |${Tool.rScript} ${new File(
          Tool.rPath,
          "produce_sample_color.R"
        ).unixPath} --g ${groupFile.unixPath}  --solution ${solutionFile.unixPath}
         |${Tool.rScript} ${Tool.rPath.unixPath}/fill_sample_color.R --g ${groupFile.unixPath}  --solution ${solutionFile.unixPath} --pc ${plot.ZScore.plotO.configFileName}
         |${Tool.rScript} ${new File(Tool.rPath, "kw_calculate.R").unixPath}
           """.stripMargin
    val plotCommands = List(
      plot.ZScore.getCommand(workspaceDir, "")
    )
    List(CommandData(workspaceDir, List(command) ::: plotCommands))
  }

  override def getHtml(missionName: String, missionId: Option[Int])(implicit
      request: Request[AnyContent],
      messages: Messages
  ): Html = {
    views.html.user.soft.diffAnaMul(missionName, missionId)
  }

  override def getMission(implicit
      request: Request[AnyContent],
      matrixFileDataDao: MatrixFileDataDao,
      messages: Messages,
      formBinding: FormBinding
  ): Tables.MissionRow = {
    val input = List(data.file, data.groupFile)
    val argJson = getArg
    MissionRow(
      id = 0,
      missionName = s"${data.missionName}",
      kind = nameStr,
      userId = userId,
      startTime = new DateTime(),
      state = "preparing",
      arg = argJson,
      input = input
    )
  }

  override def produceInputFile(
      workspaceDir: File
  )(implicit request: Request[AnyContent], dao: MyDao, formBinding: FormBinding): Any = {
    val rawDataFile = new File(workspaceDir, "AllMet_Raw.txt")
    Tool.produceRawDataFile(userId, data.file, rawDataFile)
    val groupFile = new File(workspaceDir, "group.txt")
    Tool.produceRawGroupFile(userId, data.groupFile, rawDataFile, groupFile)
  }

  override def data(implicit request: Request[AnyContent], formBinding: FormBinding) = {
    FormTool.diffAnaMulForm.bindFromRequest().get
  }

}
